package client

import (
	"context"
	"github.com/x-mod/routine"
	"sync"
)

/*
*  该部分重写了并行任务执行的包装类，增加了错误信息的记录
 */
type ParallelExecutor struct {
	execs []routine.Executor
	errs  []string
	wg    sync.WaitGroup
}

func Parallel(execs ...routine.Executor) *ParallelExecutor {
	return &ParallelExecutor{
		execs: execs,
		errs:  make([]string, len(execs)),
	}
}

func (pe *ParallelExecutor) Execute(ctx context.Context) error {
	for i, exec := range pe.execs {
		pe.wg.Add(1)
		go func(i int, exec routine.Executor) {
			defer pe.wg.Done()
			if err := exec.Execute(ctx); err != nil {
				pe.errs[i] = err.Error()
			}
		}(i, exec)
	}
	pe.wg.Wait()
	return nil
}
